import { defineConfig, loadEnv } from 'vite'
import path from 'path'
import vue from '@vitejs/plugin-vue2'
import ViteRequireContext from '@originjs/vite-plugin-require-context'
import envCompatible from 'vite-plugin-env-compatible'
import { createHtmlPlugin } from 'vite-plugin-html'
import { viteCommonjs } from '@originjs/vite-plugin-commonjs'
import { zip, progress } from 'esc-plugin'
import legacy from '@vitejs/plugin-legacy'
import { visualizer } from 'rollup-plugin-visualizer'
// https://vitejs.dev/config/
export default defineConfig(({ mode, command }) => {
  const root = process.cwd()
  const env = loadEnv(mode, root)
  const isBuild = command === 'build'
  const { VITE_BASE_API, VITE_PORT, VITE_PUBLIC_PATH, VITE_API_URL } = env
  // console.log(env)
  const plugins = [
    vue(),
    ViteRequireContext(),
    viteCommonjs(),
    envCompatible(),
    createHtmlPlugin({
      inject: {
        data: {
          title: 'r-pan-portal',
        },
      },
    }),
  ]

  if (isBuild) {
    // 兼容IE11以上版本
    plugins.push(
      legacy({
        targets: ['chrome 56'],
        additionalLegacyPolyfills: ['regenerator-runtime/runtime'],
        // renderLegacyChunks: true
      })
    )
    plugins.push(progress())
    plugins.push(
      zip({
        type: 'zip',
        archiverName: './dist.zip',
        sourceName:'dist',
        open: true,
      })
    )
    plugins.push(
      visualizer({
        open: false,
        gzipSize: true,
        brotliSize: true,
      })
    )
  }

  return {
    base: VITE_PUBLIC_PATH,
    plugins,
    build: {
      outDir: 'dist',
      assetsDir: 'static',
      chunkSizeWarningLimit: 5000,
      reportCompressedSize: false,
      sourcemap: false,
      rollupOptions: {
        output: {
          globals: {
            vue: 'Vue',
            
          },
          chunkFileNames: 'static/js/[name]-[hash].js',
          entryFileNames: 'static/js/[name]-[hash].js',
          // assetFileNames: 'static/[ext]/[name]-[hash].[ext]',
          assetFileNames: (assetInfo) => {
            var info = assetInfo.name.split('.')
            var extType = info[info.length - 1]
            if (
              /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/i.test(assetInfo.name)
            ) {
              extType = 'media'
            } else if (/\.(png|jpe?g|gif|svg)(\?.*)?$/i.test(assetInfo.name)) {
              extType = 'img'
            } else if (/\.(woff2?|eot|ttf|otf)(\?.*)?$/i.test(assetInfo.name)) {
              extType = 'fonts'
            }
            // console.log(assetInfo.name)
            return `static/${extType}/[name]-[hash][extname]`
          },
          manualChunks(id){
            if (id.includes('node_modules')) {
              return id
                .toString()
                .split('node_modules/')[1]
                .split('/')[0]
                .toString()
            }
          }
        }
      }
    },
    resolve: {
      alias: [
        // {
        //   find: /^~/,
        //   replacement: ''
        // },
        {
          find: '~@',
          replacement: path.resolve(__dirname, 'src'),
        },
        {
          find: 'module.exports =',
          replacement: 'export default',
        },
        {
          find: '@',
          replacement: path.resolve(__dirname, 'src'),
        },
        {
          find: 'vuedraggable',
          replacement: '/node_modules/vuedraggable/dist/vuedraggable.umd.js'
        }
      ],
      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue'],
    },
    server: {
      strictPort: false,
      port: VITE_PORT,
      host: '0.0.0.0',
      open: true,
      proxy: {
        // [VITE_BASE_API]: {
        //   changeOrigin: true,
        //   target: VITE_API_URL,
        //   rewrite: (path) => {
        //     const regExp = new RegExp(`^${VITE_BASE_API}`)
        //     return path.replace(regExp, '/')
        //   },
        // },
        ['/dev-api']: {
          changeOrigin: true,
          target: VITE_API_URL,
          rewrite: (path) => {
            const regExp = new RegExp(`^/dev-api`)
            return path.replace(regExp, '/')
          },
        },
      },
    },
  }
})
